package com.wushijia.highconcurrency.acomic;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * description:让普通变量享用CAS操作带来的安全性，还有AtomicLongFieldUpdate,AtomicReferenceFieldUpdate
 *
 * @author yang
 * @date 2018/6/28 20:29
 */
public class AtomicIntegerFieldUpdateDemo {

  public static class Candidate {

    int id;
    //为了确保变量被正确的读取，必须是volatile，且不支持static字段（Unsafe.objectFieldOffset()不支持静态变量）
    volatile int score;
  }

  //通过反射得到变量score,如果变量不可见（private），则会报错
  private final static AtomicIntegerFieldUpdater<Candidate> scoreUpdater = AtomicIntegerFieldUpdater.newUpdater(Candidate.class, "score");
  private static AtomicInteger allScore = new AtomicInteger(0);

  public static void main(String[] args) throws InterruptedException {
    Candidate candidate = new Candidate();

    Thread[] threads = new Thread[10000];

    for (int i = 0; i < 10000; i++) {
      threads[i] = new Thread() {
        @Override
        public void run() {
          if (Math.random() > 0.4) {
            scoreUpdater.incrementAndGet(candidate);
            allScore.incrementAndGet();
          }
        }
      };
      threads[i].start();
    }

    for (int j = 0; j < 10000; j++) {
      threads[j].join();
    }

    System.out.println(allScore.get());
    System.out.println(candidate.score);
  }

}
